/*
 *Copyright © 2015 zhaorongbao
 *招融宝
 *http://zhaorongbao.com
 *All rights reserved.
 */
package com.hanhai.zrb.backend.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.slf4j.MDC;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import com.hanhai.common.util.CommonUtil;
import com.hanhai.zrb.backend.admin.model.BackendUser;
import com.hanhai.zrb.backend.util.BackendLoginUtil;

public class BackendLogMDCInterceptor extends HandlerInterceptorAdapter {

	
	protected static Logger logger = Logger
			.getLogger(BackendLogMDCInterceptor.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		if (handler instanceof ResourceHttpRequestHandler) {
			return true;
		}
		boolean b = handler instanceof HandlerMethod;
		if (!b) {
			return true;
		}
		//BaseUser user = (BaseUser) FrontLoginUtil.getCurrentUser();
		BackendUser user = BackendLoginUtil.getCurrentUser();

		if (user != null) {
			Long id = user.getId();
			String name = user.getLoginName();
			MDC.put("loginUser", "uid:" + id + "@" + name);
		}
		String ip = CommonUtil.getRemoteIp(request);
		MDC.put("userip", ip);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		MDC.remove("loginName");
		MDC.remove("userip");
		super.afterCompletion(request, response, handler, ex);
	}
}
